<template>
    <template v-if="inited && device.connectStatus == 0">
        <view class="offline">设备已掉线</view>
    </template>
    <view class="page" v-if="inited">
        <view class="_wrap">
            <view style="height: 100%;overflow-y: auto;">
                <view class='p-l-r' style="flex:1">
                    <view class="module">
                        <view class="moduleTitle">选择枪</view>
                        <view class="body portContainer">
                            <template v-for="port in ports" : key="port">
                                <view class="port" :class="{selected : formData.port == port.portNo, disabled : port.status != 0}" @tap="selectPort(port.portNo)">
                                    <view>{{ PORT_NAME[port.portNo] }}</view>
                                    <view>/</view>
                                    <view>{{ PORT_STATUS[port.status] }}</view>
                                </view>
                            </template>
                        </view>
                    </view>

                    <view class="module m-t-40">
                        <view class="moduleTitle">充电类型</view>
                        <view class="body">
                            <view class="pay-type">
                                <view class="item" :class="{selected : formData.mode == 1}" @tap="selectMode(1)">{{ CHARGE_FEE_MODE[1] }}</view>
                                <view class="item" :class="{selected : formData.mode == 0}" @tap="selectMode(0)">{{ CHARGE_FEE_MODE[0] }}</view>
                                
                                <!-- <view class="item" :class="{selected : formData.mode == 2}" @tap="selectMode(2)">{{ CHARGE_FEE_MODE[2] }}</view> -->
                            </view>   
                            <view class="m-t-30 number-input">
                                <view>{{ CHARGE_FEE_MODE[formData.mode]}}({{ formData.mode == 0 ? '小时' : formData.mode == 1 ? '度' : '元' }})</view>
                                <nut-input-number type="digit" decimal-places="1" class="inputNumber" :min="0" v-model="formData.chargeNumber" button-size="30" input-width="60" />
                            </view>
                        </view>
                    </view>
                    <template v-if="!device.private">
                        <view class="module m-t-40">
                            <view class="moduleTitle">收费标准</view>
                            <view class="body current-pricing" v-if="pricing">
                                <template v-if="device.chargeType == 1">
                                    <view class="top">
                                        <view class="amount">当前时段1.0600元/每度</view>
                                        <navigator class="nav">收费详情</navigator>
                                    </view>
                                    <view class="detail m-t-20">
                                        <view class="item">
                                            <view>电价</view>
                                            <view class="m-t-10 amount">0.96元/度</view>
                                        </view>
                                        <view class="item">
                                            <view>服务费</view>
                                            <view class="m-t-10 amount">0.96元/度</view>
                                        </view>
                                    </view>
                                </template>
                                <template v-else>
                                    <view class="detail">
                                        <view class="item">
                                            <view>电价</view>
                                            <view class="m-t-10 amount">{{ pricing.price }}元/度</view>
                                        </view>
                                        <view class="item">
                                            <view>服务费</view>
                                            <view class="m-t-10 amount">{{ pricing.service }}元/度</view>
                                        </view>
                                    </view>
                                </template>
                            </view>
                        </view>
                        <view v-if="device.connectStatus == 1" class="module m-t-40">
                            <view class="moduleTitle">余额</view>
                            <view class="body current-pricing">
                                <view class="top">
                                    <view class="amount">{{ balance }}元</view>
                                    <navigator class="nav" url="/subPages/wallet/index">去充值</navigator>
                                </view>
                            </view>
                        </view>
                    </template>
                </view>
            </view>
            <view v-if="device.connectStatus == 1" class='bottomAction p-box'>
                <template v-if="!device.private">
                    <nut-button v-if="pricing" type="success" block size="large" @tap="charge">下单充电({{ amountComputed }}元)</nut-button>
                </template>
                <nut-button v-else type="success" block size="large" @tap="privateCharge">启动充电</nut-button>
            </view>
        </view>
    </view>

    <ActionSheet v-model:visible="payTypeVisible" @choose="choosePayType">
        <view class="payTypeItems">
            <view class="item" @tap="choosePayType(1)">支付分支付</view>
            <view class="item" @tap="choosePayType(2)">余额支付</view>
            <view class="item cancel" @tap="closeVisible">取消</view>
        </view>
    </ActionSheet>
    <LoadingPage v-if="!inited" />
</template>

<script lang="ts" setup>
    import { ActionSheet } from '@nutui/nutui-taro';
    import "@nutui/nutui-taro/dist/packages/actionsheet/index.scss";

    import { queryFreePayApi } from '@/api/User';
    import { balanceApi } from '@/api/Wallet';
    import { chargeApi, chargeResApi } from '@/api/Charge'
    import { ref } from 'vue';
    import { CHARGE_FEE_MODE, PORT_NAME, PORT_STATUS } from '@/constant'
    import { useRouter } from '@tarojs/taro';
    import { infoApi } from '@/api/Device';
    import { hideLoading, showLoading, showModal, redirectTo, openBusinessView, requestSubscribeMessage, useDidShow } from '@/utils/framework';
    import LoadingPage from '@/components/LoadingPage/index.vue'
    import { computed } from 'vue';
    import { privateChargeResApi } from '@/api/PrivateChargeRecord';
    import { useUserStore } from '@/stores/user';
    import { chargeFinishMsgTemplateApi } from '@/api/Common';
    
    const inited = ref(false)

    const router = useRouter()
    const deviceId = Number(router.params.deviceId)
    let queryCount = 0
    
    const device = ref<any>()
    const pricing = ref<any>()
    const station = ref<any>()
    const ports = ref<Array<{status:0|1, portNo:number}>>([])
    
    const payTypeVisible = ref(false)
    const userStore = useUserStore()

    function closeVisible() {
        payTypeVisible.value = false
    }

    const templateIds:string[] = []
    

    const formData = ref({
        port : 0,
        chargeNumber : 1,
        mode : 1,
        payType : 2
    })

    const balance = ref(0)
    function queryBalance(){
        balanceApi().then(res => {
            if(res.success) {
                balance.value = res.data
            }
        })
    }

    const amountComputed = computed(() => {
        if(!pricing.value) return 0
        const price = Number(pricing.value.price)
        const service = Number(pricing.value.service)

        if(formData.value.mode == 0) { //按时间
            return (Number(formData.value.chargeNumber * pricing.value.hourKwh) * (price + service)).toFixed(2)
        }else {
            return (formData.value.chargeNumber * (price + service)).toFixed(2)
        }
    })


    function selectPort(port:number) {
        if(ports.value[port - 1].status != 0) return
        formData.value.port = port
    }
    function selectMode(mode:number) {
        formData.value.mode = mode
    }

    infoApi(deviceId).then(res => {
        if(!res.success) {
            showModal(res.msg);
            return
        }
        if(res.data) {
            if(!res.data.device.private) { //不是私人充电的
                if(res.data.device.connectStatus == 1){
                    queryBalance()
                    chargeFinishMsgTemplateApi().then(r => {
                        if(r.data) {
                            templateIds.push(r.data)
                        }
                    })
                }

                if(res.data.station) {
                    station.value = res.data.station
                }

                if(res.data.pricing) {
                    pricing.value = res.data.pricing
                }
                
            }

            device.value = res.data.device
            for(let i = 1; i <= device.value.portCount; i ++) {
                let port:any = {portNo : i, status : 0}
                if(device.value.portStatus) {
                    port.status = device.value.portStatus[i - 1]
                    if(port.status == 0) {
                        formData.value.port = i
                    }
                }

                ports.value.push(port)
            }

            

            
        }

        inited.value = true
    })
    
    
    //私人充电
    async function privateCharge() {
        if(formData.value.port == 0) {
            showModal('请选择枪号')
            return
        }

        doCharge()
    }

    async function charge() {
        if(formData.value.port == 0) {
            showModal('请选择枪号')
            return
        }

        if(templateIds.length > 0) {
            await requestSubscribeMessage(templateIds)
        }

        payTypeVisible.value = true
    }

    async function choosePayType(payType:number) {
        payTypeVisible.value = false
        formData.value.payType = payType
        if(payType == 1) { //支付分支付
            doCharge()

            return
            if(userStore.payscore) { //已经授权了
                doCharge()
                return
            }

            //查询用户是否已经开通免密支付
            const r = await queryFreePayApi()
            if(!r.success) {
                hideLoading()
                showModal('支付失败')
                return
            }else {
                if(r.data.status) { //已经获取到授权
                    userStore.payscore = true
                    doCharge()
                }else {
                    if(!r.data.status) { //需要发起授权
                        openBusinessView(
                            'wxpayScoreEnable',
                            r.data.code,
                            (e) => {
                                console.log(e)
                                userStore.payscore = true
                                doCharge()
                            }
                        )
                    }
                }


                
            }
        }else { //余额支付
            doCharge()
        }
    }

    async function doCharge() {
        queryCount = 0
        showLoading()
        const params = {...formData.value}
        params.chargeNumber = Number(params.chargeNumber)

        const res = await chargeApi({
            deviceId,
            ...params
        })

        if(res.success) {
            setTimeout(() => {
                queryChargeRes(res.data as number)
            }, 5000)
            
        }else {
            hideLoading()
            showModal(res.msg)
        }
    }

    async function queryChargeRes(orderId:number) {
        const res = device.value.private == 1 ? (await privateChargeResApi(orderId)) : (await chargeResApi(orderId))
        if(!res.success) {
            hideLoading()
            showModal('充电失败')
        }else if(res.data == 0) { //继续查询
            if(queryCount < 3) {
                setTimeout(() => {
                    queryChargeRes(orderId)
                }, 5000)
            }else {
                hideLoading()
                showModal('充电失败')
            }
        }else if(res.data == 1) { //开始充电了
            hideLoading()
            //跳到充电页面
            let url = '/chargeOrder/pages/charging/index?from=charge'
            if(device.value.private == 1) {
                url += (`&private=1&device=${deviceId}`)
            }
            redirectTo(url)
        }else { //失败了
            hideLoading()
            showModal('充电失败')
        }
        
        queryCount ++
    }


    useDidShow(() => {
        if(inited.value) {
            queryBalance()
        }
        
    })
</script>

<style lang="scss" src="./index.scss" module></style>